﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Reflection;

using SharedGenomics.Workbench.Core;
using SharedGenomics.Workbench.Models;
using SharedGenomics.Workbench.Views;
using SharedGenomics.Workbench.Services;
using SharedGenomics.Domain;
using SharedGenomics.Annotations;

namespace SharedGenomics.Workbench.Presenters
{
    public class AnnotationResultsPresenter : Presenter
    {
        private readonly IAnnotationResultsView resultsView;
        private readonly ICoverflowUriResolver coverflowUriResolver;
        private readonly IAnnotationSessionManager sessionManager;

        public AnnotationResultsPresenter(IAnnotationResultsView view, IAnnotationSessionManager sessionManager, ICoverflowUriResolver coverflowUriResolver)
            : base(view)
        {
            //register for view events
            view.ViewLoaded += (o, e) => { this.GetAvailableSessions(); };
            view.RefreshSessionsClicked += (o, e) => { this.GetAvailableSessions(); };
            view.SelectedSessionIdChanged += View_SelectedSessionIdChanged;
            view.ImportanceCheckedChanged += View_ImportanceCheckedChanged;

            //set private properties
            this.resultsView = view;
            this.sessionManager = sessionManager;
            this.coverflowUriResolver = coverflowUriResolver;
        }

        private void GetAvailableSessions()
        {
            this.resultsView.AvailableSessions = this.sessionManager.GetAnnotationSessionsForUser();
        }

        private void View_SelectedSessionIdChanged(object sender, EventArgs e)
        {
            this.SelectedSessionStateChanged();
        }

        private void View_ImportanceCheckedChanged(object sender, EventArgs e)
        {
            this.SelectedSessionStateChanged();
        }

        private void SelectedSessionStateChanged()
        {
            Guid? sessionId = this.resultsView.SelectedSessionId;
            if (sessionId.HasValue)
            {
                Uri targetUri = this.coverflowUriResolver.ResolveUri(sessionId.Value, this.SelectedViewDisplayImportance);
                this.resultsView.NavigateTo(targetUri);
            }
        }

        private SessionAnnotationDisplayImportance SelectedViewDisplayImportance
        {
            get
            {
                if (this.resultsView.IsImportanceHighlightChecked) return SessionAnnotationDisplayImportance.Highlight;
                else if (this.resultsView.IsImportanceImportantChecked) return SessionAnnotationDisplayImportance.Important;
                else return SessionAnnotationDisplayImportance.All;
            }
        }
    }
}
